<template>
  <div class="login-warpper">
    <title-bar :titleText="$route.meta.title">
      <!-- 返回按钮 -->
      <slot name="left">
        <i
          class="icon iconfont icon-back back-btn"
          @click="back()"
        ></i>
      </slot>
      <slot>
        <!-- 标题 -->
        <span class="title-text"></span>
      </slot>
      <!-- 右上角按钮 -->
      <slot name="right">
        <div
          class="flex-h flex-hc flex-vc right-btn"
          style="z-index: 99;"
          @click="rightFunc"
        > 注册</div>
      </slot>
    </title-bar>
    <!-- 顶部错误信息提示 -->
    <div
      v-show="isErrorMsgShow"
      class="fontsize24 error-msg-warpper"
    >账号或密码错误，请重新输入</div>
    <div class="input-warpper">
      <!-- 手机号输入组件 -->
      <username-input
        ref="myUsername"
        :username="username"
      ></username-input>
      <!-- 密码输入组件 -->
      <password-input
        ref="myPassword"
        :password="password"
        :isShowPwdIcon="isShowPwdIcon"
      ></password-input>
      <!-- <div class="flex-h flex-vc phone-wapper">
        <i class="icon iconfont icon-mphone fontsize48"></i>
        <input
          type="text"
          class="input-cmomon flex1 input-phone"
          v-model.trim="phone"
          placeholder="请输入手机号码"
        />
        <i
          v-show="phone?true:false"
          class="icon iconfont icon-cancel-o fontsize36"
          @click="clearUsername()"
        ></i>
      </div> -->
      <!-- <div class="flex-h flex-vc password-wapper">
        <i class="icon iconfont icon-password fontsize48"></i>
        <input
          :type="isShowPassword?'text':'password'"
          class="input-cmomon flex1 input-password"
          v-model="password"
          placeholder="请输入密码"
        />
        <i
          v-show="password?true:false"
          class="icon iconfont icon-cancel-o fontsize36"
          @click="clearPassword()"
        ></i>
        <i
          class="icon iconfont icon-eye fontsize48"
          :class="isShowPassword?'eye-show':''"
          @click="isShowPassword=!isShowPassword"
        ></i>
      </div> -->
      <!-- <ul class="input-warpper">
        <li class="flex-h flex-vc phone-wapper">
          <i class="icon iconfont icon-mphone fontsize48"></i>
          <input
            type="text"
            class="input-cmomon flex1 input-phone"
            v-model.trim="phone"
            placeholder="请输入手机号码"
          />
          <i
            v-show="phone?true:false"
            class="icon iconfont icon-cancel-o fontsize36"
            @click="clearUsername()"
          ></i>
        </li>
        <li class="flex-h flex-vc password-wapper">
          <i class="icon iconfont icon-password fontsize48"></i>
          <input
            :type="isShowPassword?'text':'password'"
            class="input-cmomon flex1 input-password"
            v-model="password"
            placeholder="请输入密码"
          />
          <i
            v-show="password?true:false"
            class="icon iconfont icon-cancel-o fontsize36"
            @click="clearPassword()"
          ></i>
          <i
            class="icon iconfont icon-eye fontsize48"
            :class="isShowPassword?'eye-show':''"
            @click="isShowPassword=!isShowPassword"
          ></i>
        </li>
      </ul> -->
      <button
        class="baseBgColorNoActive fontsize28 login-btn"
        @click="passwordLogin()"
      >登录</button>
      <div class="flex-h flex-hsb fontsize24 other-way-warpper">
        <p @click="smscodeLogin()">短信验证码登录</p>
        <p @click="forgetPassword()">忘记密码</p>
      </div>
    </div>
    <div class="third-party-warpper">
      <div>
        <ul class="flex-h flex-vc flex-hsb">
          <li class="split-line"></li>
          <li class="fontsize22 third-party-text">第三方登录</li>
          <li class="split-line"></li>
        </ul>
        <div class="flex-h flex-hc">
          <img
            class="wechat-logo"
            src="./../assets/login-wechat.png"
            @click="wechatLogin()"
          />
        </div>
      </div>
    </div>
    <img
      v-if="isShowBottomImg"
      class="bottom-img"
      src="./../assets/login-bottom.png"
    />
  </div>
</template>

<script>
import { TitleBar } from 'vue-xb-ui-depot'
import UsernameInput from '../components/UsernameInput'
import PasswordInput from '../components/PasswordInput'
import md5 from 'js-md5'
import { login, thirdLogin, getUnreadMessageCount } from '../api/api'
import { setUserInfoJumpLogin, getUsername } from '../utils/loginCommon'
import { validatePromiseAll } from '../utils/validateForm'
export default {
  components: {
    usernameInput: UsernameInput,
    PasswordInput: PasswordInput,
    TitleBar
  },
  data() {
    return {
      username: '',
      password: '',
      isShowPwdIcon: true, // 密码眼睛图标是否展示
      isShowPassword: false, // 密码是否明文展示
      isErrorMsgShow: false, // 是否展示登录错误提示
      isShowBottomImg: window.isShowBottomImg// 是否展示底部图片
    }
  },
  mounted() {
    this.$refs.myUsername.username = getUsername()// 本地缓存记住当前账号
  },
  methods: {
    back() {
      this.$AppRouterUtils.goHome()// 回到首页
    },
    rightFunc() { // 注册
      this.$router.push({ name: 'register' })
    },
    passwordLogin() { // 登录
      let username = this.$refs.myUsername.username
      let password = this.$refs.myPassword.password

      validatePromiseAll({
        checkArray: [{
          type: 'username',
          value: username
        }, {
          type: 'password',
          value: password
        }],
        successCallback: (dataArray) => {
          // console.log(dataArray)
          login(
            username,
            md5(password),
            this.$parent.cid,
            this.$parent.mobileModel,
            this.$parent.mobileVersion,
            this.$parent.appVersion
          ).then(res => {
            window.localStorage.setItem('XIAOBUSESSION', res.SESSION_ID)
            // 获取用户消息未读数
            getUnreadMessageCount().then(resp => {
              // 用户消息未读数传给底层
              this.$System.then(System => {
                System.syncUnreadMessageCount(
                  resp.COUNT,
                  () => {
                    console.log('未读总数传递成功')
                  },
                  () => {
                    console.log('未读总数传递失败')
                  }
                )
              })
              res.INIT = '0'
              res.PHONE = username
              this.$toastMsg('登录成功')
              setUserInfoJumpLogin(res, this)
            })

            // res.IS_LOGIN = 1
            // res.INIT = 0
            // window.localStorage.setItem('fdaheoibhdio3bcoabfcil', username)
            // window.localStorage.setItem('XIAOBUSESSION', res.SESSION_ID)
            // window.localStorage.setItem('XIAOBUUSERBEAN', JSON.stringify(res))
            // localStorage.setItem('XIAOBUSESSION', res.SESSION_ID)
            // res.PHONE = username
            // res.IS_LOGIN = 1
            // UserBeanUtils.setUserInfo(res)
            // this.$toastMsg('登录成功')
            // window.location.href = 'xbapp://goback?loginsuccess=1'
          }).catch(err => {
            console.log(err)
            // USR100007：密码错误，USR100008：会员不存在
            if (err.error.data.RSPCD === 'USR100007' || err.error.data.RSPCD === 'USR100008') {
              this.isErrorMsgShow = true
            } else {
              this.isErrorMsgShow = false
              this.$toastMsg(err.error.data.RSPMSG || err.error.data.RSPCD)
            }
          })
        },
        errorCallback: (error) => {
          this.$toastMsg(error)
        }
      })

      // let result = validateForm([{
      //   key: 'username',
      //   value: username
      // }, {
      //   key: 'password',
      //   value: password
      // }], this)
      // console.log('result-------->', result)

      // if (username === '') {
      //   this.$toastMsg('请输入手机号码')
      //   return false
      // } else if (!/^1[3-9]\d{9}$/.test(username)) {
      //   this.$toastMsg('手机号码格式不正确')
      //   return false
      // }
      // if (password === '') {
      //   this.$toastMsg('请输入密码')
      //   return false
      // } else if (password.length < 6 || password.length > 20) {
      //   this.$toastMsg('请输入密码(6-20)')
      //   return false
      // } else {
      //   password = md5(password)
      // }
      // login(
      //   username,
      //   password,
      //   this.$parent.cid,
      //   this.$parent.mobileModel,
      //   this.$parent.mobileVersion,
      //   this.$parent.appVersion
      // ).then(res => {
      //   window.localStorage.setItem('XIAOBUSESSION', res.SESSION_ID)
      //   // 获取用户消息未读数
      //   getUnreadMessageCount().then(resp => {
      //     // 用户消息未读数传给底层
      //     this.$System.then(System => {
      //       System.syncUnreadMessageCount(
      //         resp.COUNT,
      //         () => {
      //           console.log('未读总数传递成功')
      //         },
      //         () => {
      //           console.log('未读总数传递失败')
      //         }
      //       )
      //     })

      //     res.INIT = '0'
      //     res.PHONE = username
      //     this.$toastMsg('登录成功')
      //     setUserInfoJumpLogin(res)
      //   })

      //   // res.IS_LOGIN = 1
      //   // res.INIT = 0
      //   // window.localStorage.setItem('fdaheoibhdio3bcoabfcil', username)
      //   // window.localStorage.setItem('XIAOBUSESSION', res.SESSION_ID)
      //   // window.localStorage.setItem('XIAOBUUSERBEAN', JSON.stringify(res))
      //   // localStorage.setItem('XIAOBUSESSION', res.SESSION_ID)
      //   // res.PHONE = username
      //   // res.IS_LOGIN = 1
      //   // UserBeanUtils.setUserInfo(res)
      //   // this.$toastMsg('登录成功')
      //   // window.location.href = 'xbapp://goback?loginsuccess=1'
      // }).catch(err => {
      //   console.log(err)
      //   // USR100007：密码错误，USR100008：会员不存在
      //   if (err.error.data.RSPCD === 'USR100007' || err.error.data.RSPCD === 'USR100008') {
      //     this.isErrorMsgShow = true
      //   } else {
      //     this.isErrorMsgShow = false
      //     this.$toastMsg(err.error.data.RSPMSG || err.error.data.RSPCD)
      //   }
      // })
    },
    smscodeLogin() { // 短信验证登录
      this.$router.push({ name: 'smscodeLogin' })
    },
    forgetPassword() { // 忘记密码
      this.$router.push({ name: 'forgetPassword' })
    },
    wechatLogin() { // 微信登录
      this.$ThirdParty.then(ThirdParty => {
        ThirdParty.doAuthorizedLogin(
          'Wechat',
          msg => {
            let wxInfo = JSON.parse(msg)
            thirdLogin(
              wxInfo.unionid,
              wxInfo.nickname,
              wxInfo.sex,
              wxInfo.headimgurl,
              wxInfo.country,
              wxInfo.province,
              wxInfo.city,
              this.$parent.cid,
              this.$parent.mobileModel,
              this.$parent.mobileVersion,
              this.$parent.appVersion
            ).then(res => {
              window.localStorage.setItem('XIAOBUSESSION', res.SESSION_ID)
              if (res.PHONE) {
                // 获取用户消息未读数
                getUnreadMessageCount().then(resp => {
                  // 用户消息未读数传给底层
                  this.$System.then(System => {
                    System.syncUnreadMessageCount(
                      resp.COUNT,
                      () => {
                        console.log('未读总数传递成功')
                      },
                      () => {
                        console.log('未读总数传递失败')
                      }
                    )
                  })

                  this.$toastMsg('登录成功')
                  setUserInfoJumpLogin(res, this)
                })
              } else {
                this.$router.push({
                  name: 'bindPhoneLogin',
                  query: {
                    nickName: wxInfo.nickname,
                    headPortrait: wxInfo.headimgurl
                  }
                })
              }
            })
          },
          err => {
            console.log(err + 'error')
          }
        )
      })

      // this.$router.push({ name: 'bindPhoneLogin' })
    }
  }
}
</script>

<style scoped>
.right-btn {
  color: #999;
}
.login-warpper {
  width: 100%;
}
/* 登录错误提示 */
.error-msg-warpper {
  color: #fff;
  font-family: Helvetica;
  width: 750px;
  height: 34px;
  line-height: 34px;
  text-align: center;
  background-color: #ffcea0;
}
/* 输入组件包裹成 */
.input-warpper {
  padding: 60px 30px 0 30px;
}
/* 输入模块 */
.phone-wapper,
.password-wapper {
  width: 690px;
  height: 112px;
  border-bottom: 1px solid #f2f5f6; /*no*/
}
/* 手机号、密码图标 */
.icon-mphone,
.icon-password {
  color: #333;
  width: 60px;
  height: 60px;
  line-height: 60px;
  text-align: center;
}
/* 默认输入框样式 */
.input-cmomon {
  font-size: 32px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #333;
  height: 45px;
  line-height: 45px;
  margin: 0 26px;
  border: none;
}
/* .icon-cancel-o {
  color: #ccc;
} */
/* 密码区 */
/* .password-wapper {
  margin-top: 32px;
} */
/* 清空、眼睛图标样式 */
/* .icon-cancel-o,
.icon-eye {
  color: #ccc;
  width: 60px;
  height: 60px;
  line-height: 60px;
  text-align: center;
}
.eye-show {
  color: #1dc994;
} */
/* 登录按钮 */
.login-btn {
  color: #fff;
  width: 690px;
  height: 80px;
  line-height: 80px;
  margin-top: 100px;
  border-radius: 8px; /*px*/
  border: none;
}
.other-way-warpper {
  color: #999;
  margin-top: 20px;
}
.split-line {
  width: 260px;
  height: 1px; /*no*/
  background: #cccccc;
}
.third-party-warpper {
  width: 100%;
  position: absolute;
  left: 0;
  bottom: 250px;
}
.third-party-warpper > div {
  padding: 0 30px;
}
.third-party-text {
  color: #999;
  /* margin: 0 30px; */
}
.wechat-logo {
  width: 102px;
  height: 102px;
  margin-top: 25px;
}
/* 底部图片 */
.bottom-img {
  width: 750px;
  height: 156px;
  position: absolute;
  bottom: 0;
  left: 0;
}
</style>
